<!--车辆管理页-->
<template>
  <div style="background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">住院信息管理</span>
  </div>

  <!-- 搜索卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="患者姓名">
        <el-input 
          placeholder="请输入" 
          style="width:220px;" 
          v-model="searchForm.patientName"
          @keydown.enter="loadHospitalList"
        ></el-input>
      </el-form-item>
      <el-form-item label="入院时间">
        <el-date-picker
          v-model="searchForm.intime"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width:220px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadHospitalList">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">新增住院</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 车辆列表 -->
  <el-card style="margin:20px;">
    <el-table :data="hospitalList" v-loading="loading" border stripe style="width: 100%">
      <el-table-column prop="floor" label="楼层" width="100" align="center"/>
      <el-table-column prop="bed" label="床号" width="100" align="center"/>
      <el-table-column prop="door" label="房间号" width="100" align="center"/>
      <el-table-column prop="medicalName" label="疾病名称" width="180" align="center"/>
      <el-table-column prop="name" label="患者姓名" width="120" align="center"/>
      <el-table-column prop="intime" label="入院时间" width="180" align="center"/>
      <el-table-column prop="outtime" label="出院时间" width="180" align="center"/>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 新增/编辑对话框 -->
  <el-dialog 
    :title="dialogTitle" 
    v-model="dialogVisible" 
    width="50%"
    :before-close="handleClose"
  >
    <el-form 
      ref="formRef"
      :model="hospitalForm"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="楼层">
            <el-input 
              v-model="hospitalForm.floor" 
              placeholder="请输入楼层"
              maxlength="10"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="床号">
            <el-input 
              v-model="hospitalForm.bed" 
              placeholder="请输入床号"
              maxlength="10"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="房间号">
            <el-input 
              v-model="hospitalForm.door" 
              placeholder="请输入房间号"
              maxlength="10"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="疾病名称">
            <el-input 
              v-model="hospitalForm.medicalName" 
              placeholder="请输入疾病名称"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="患者姓名">
        <el-input 
          v-model="hospitalForm.name" 
          placeholder="请输入患者姓名"
          maxlength="20"
        ></el-input>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入院时间">
            <el-date-picker
              v-model="hospitalForm.intime"
              type="date"
              placeholder="选择入院时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              @change="validateDate"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出院时间">
            <el-date-picker
              v-model="hospitalForm.outtime"
              type="date"
              placeholder="选择出院时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              @change="validateDate"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "@/axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索表单
const searchForm = ref({
  patientName: '',
  intime: ''
});

// 数据列表
const hospitalList = ref([]);
// 加载状态
const loading = ref(false);
// 对话框显示状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增住院信息');

// 表单对象
const hospitalForm = ref({
  id: null,
  floor: '',
  bed: '',
  door: '',
  medicalName: '',
  name: '',  // 患者姓名
  intime: '',
  outtime: ''
});

// // 表单规则
// const rules = {
//   floor: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
//   bed: [{ required: true, message: '请输入床号', trigger: 'blur' }],
//   door: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
//   medicalName: [{ required: true, message: '请输入疾病名称', trigger: 'blur' }],
//   name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
//   intime: [{ required: true, message: '请选择入院时间', trigger: 'change' }]
// };

// 表单引用
const formRef = ref(null);

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    patientName: '',
    intime: ''
  };
  loadHospitalList();
};

// 加载住院列表
const loadHospitalList = async () => {
  loading.value = true;
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    loading.value = false;
    return;
  }

  try {
    const { data: res } = await axios.get("/admin/hospitalization/select", {
      params: searchForm.value,
      headers: {
        'Authorization': token
      }
    });
    if (res.code === 2000) {
      hospitalList.value = res.data;
    } else {
      ElMessage.error(res.message || '查询失败');
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
    } else {
      ElMessage.error('查询失败：' + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增住院信息';
  hospitalForm.value = {
    id: null,
    floor: '',
    bed: '',
    door: '',
    medicalName: '',
    name: '',
    intime: '',
    outtime: ''
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑住院信息';
  hospitalForm.value = { ...row };
  dialogVisible.value = true;
};

// 校验日期
const validateDate = () => {
  const intime = hospitalForm.value.intime;
  const outtime = hospitalForm.value.outtime;
  if (intime && outtime && new Date(outtime) <= new Date(intime)) {
    ElMessage.error('出院时间不能早于入院时间!');
    hospitalForm.value.outtime = '';
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    await formRef.value.validate();
    
    const url = hospitalForm.value.id ? '/admin/hospitalization/update' : '/admin/hospitalization/add';
    
    const { data: res } = await axios.post(url, hospitalForm.value, {
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
    
    if (res.code === 2000) {
      ElMessage.success(hospitalForm.value.id ? '更新成功' : '新增成功');
      dialogVisible.value = false;
      loadHospitalList();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
    } else {
      ElMessage.error('操作失败：' + error.message);
    }
  }
};

// 删除住院信息
const handleDelete = async (id) => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    await ElMessageBox.confirm('确认删除该住院记录吗？', '提示', {
      type: 'warning'
    });
    const { data: res } = await axios.post(`/admin/hospitalization/delete/${id}`, null, {
      headers: {
        'Authorization': token
      }
    });
    if (res.code === 2000) {
      ElMessage.success('删除成功');
      loadHospitalList();
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};

// 关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
    type: 'warning'
  }).then(() => {
    dialogVisible.value = false;
    hospitalForm.value = {};
  }).catch(() => {});
};

onMounted(() => {
  loadHospitalList();
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
}

/* 添加搜索框中新增按钮的样式 */
.el-form-item:last-child {
  margin-right: 0;
  margin-bottom: 0;
}
</style>